package com.keelau.jxbrowser;

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.PopupContainer;
import com.teamdev.jxbrowser.chromium.PopupHandler;
import com.teamdev.jxbrowser.chromium.PopupParams;
import com.teamdev.jxbrowser.chromium.events.FinishLoadingEvent;
import com.teamdev.jxbrowser.chromium.events.LoadAdapter;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.*;
import java.awt.*;
import java.util.List;

public class MyBrowserView  {

    Browser browser;

    Logger logger = LoggerFactory.getLogger(this.getClass());

    public MyBrowserView(Browser browser){
        if(browser==null)
            browser = new Browser();
        else{
            this.browser = browser;
        }
    }

    public BrowserView getSwingBrowserView(){
        BrowserView view = new BrowserView(browser);

        return  view;
    }

    public com.teamdev.jxbrowser.chromium.javafx.BrowserView getFXBrowserView(){
        com.teamdev.jxbrowser.chromium.javafx.BrowserView view = new com.teamdev.jxbrowser.chromium.javafx.BrowserView();


        return  view;
    }

    public void addBrowserListener(Browser browser,int index){
        browser.addLoadListener(new LoadAdapter() {
            @Override
            public void onFinishLoadingFrame(FinishLoadingEvent event) {
                if (event.isMainFrame()) {
                    printFramesHierarchy(event.getBrowser(), Browser.MAIN_FRAME_ID);
                }
                String title = browser.getTitle();

               // jTabbedPane.setTitleAt(index,browser.getTitle());
            }
        });

        addbrowserPopWindowHandler(browser);
    }

    public  void printFramesHierarchy(Browser browser, long parentFrameId) {
        List<Long> childFrameIds = browser.getFramesIds(parentFrameId);
        for (Long childFrameId : childFrameIds) {
            logger.info("Child Frame: " + childFrameId );//+ ", HTML: " + browser.getHTML(childFrameId));
            printFramesHierarchy(browser, childFrameId);
        }
    }
    public void addbrowserPopWindowHandler(Browser browser){
        browser.setPopupHandler(new PopupHandler() {
            public PopupContainer handlePopup(PopupParams params) {
                return new PopupContainer() {
                    public void insertBrowser(final Browser browser, final Rectangle initialBounds) {
                        SwingUtilities.invokeLater(new Runnable() {
                            @Override
                            public void run() {
                               // createTabBrowser(browser,"");
                            }
                        });
                    }
                };
            }
        });
    }
}
